package com.wuhuahe.learning.lagou.service.autodeliver.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wuhuahe.learning.lagou.servie.feign.api.ResumeFeignApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/autodeliver")
public class AutodeliverController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;



    @Autowired
    private ResumeFeignApi resumeFeignApi;

    /**
     * 使用ribbon负载均衡,Feign调用
     *
     * @param userId
     * @return
     */
    @GetMapping("/checkStateFeign/{userId}")
    public String findResumeOpenStateWithFeign(@PathVariable Long userId) {
        String state = resumeFeignApi.findDefaultResumeState3(userId);
        return state;
    }

    /**
     * 使用ribbon负载均衡
     *
     * @param userId
     * @return
     */
    @GetMapping("/checkState3/{userId}")
    public String findResumeOpenState3(@PathVariable Long userId) {
        String url = "http://lagou-service-resume/resume/openstate2/" + userId;  // 指定服务名
        String forObject = restTemplate.getForObject(url, String.class);
        return forObject;
    }


    @GetMapping("/checkState2/{userId}")
    public Integer findResumeOpenState2(@PathVariable Long userId) {

        List<ServiceInstance> instances = discoveryClient.getInstances("LAGOU-SERVICE-RESUME");
        for (ServiceInstance instance : instances) {
            System.out.println(instance);
        }

        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();


        String url = "http://" + host + ":" + port + "/resume/openstate/" + userId;  // 指定服务名
        System.out.println("url= " + url);
        Integer forObject = new RestTemplate().getForObject(url, Integer.class);
        return forObject;
    }


    @GetMapping("/checkState/{userId}")
    public Integer findResumeOpenState(@PathVariable Long userId) {
        String url = "http://localhost:8080/resume/openstate/" + userId;  // 指定服务名
        Integer forObject = restTemplate.getForObject(url, Integer.class);
        return forObject;
    }


    // 使用Hystrix熔断器
    @HystrixCommand(
            threadPoolKey = "findResumeOpenStateTimeout",
            threadPoolProperties = {
                   @HystrixProperty(name = "coreSize", value = "1"),
                    @HystrixProperty(name="maxQueueSize", value="20")
            },
            commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    @GetMapping("/checkStateTimeout/{userId}")
    public String findResumeOpenStateTimeout(@PathVariable Long userId) {
        String url = "http://lagou-service-resume/resume/openstate3/" + userId;
        String forObject = restTemplate.getForObject(url, String.class);
        return forObject;
    }


    // 使用Hystrix熔断器
    @HystrixCommand(
            threadPoolKey = "findResumeOpenStateFallback",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "2"),
                    @HystrixProperty(name="maxQueueSize", value="20")
            },
            commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
                    ,
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "8000"), // 判断是否触发跳闸时间窗口
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value = "3000")
    }, fallbackMethod = "myFallback")
    @GetMapping("/checkStateFallback/{userId}")
    public String findResumeOpenStateFallback(@PathVariable Long userId) {
        String url = "http://lagou-service-resume/resume/openstate3/" + userId;
        String forObject = restTemplate.getForObject(url, String.class);
        return forObject;
    }

    public String myFallback(Long userId){
        return "Fallback " + userId;
    }
}
